const tenantService = require('../services/tenantService');
const Joi = require('joi');

// 验证模式
const schemas = {
  createTenant: Joi.object({
    name: Joi.string().min(1).max(100).required(),
    domain: Joi.string().min(3).max(63).pattern(/^[a-z0-9-]+$/).required(),
    email: Joi.string().email().required(),
    adminUser: Joi.object({
      email: Joi.string().email().required(),
      password: Joi.string().min(8).required(),
      firstName: Joi.string().min(1).max(50).required(),
      lastName: Joi.string().min(1).max(50).required()
    }).optional()
  }),
  
  updateTenant: Joi.object({
    name: Joi.string().min(1).max(100).optional(),
    domain: Joi.string().min(3).max(63).pattern(/^[a-z0-9-]+$/).optional(),
    email: Joi.string().email().optional(),
    status: Joi.string().valid('active', 'inactive', 'suspended').optional(),
    plan: Joi.string().valid('free', 'basic', 'premium', 'enterprise').optional()
  }),
  
  updateSettings: Joi.object({
    theme: Joi.string().valid('light', 'dark', 'auto').optional(),
    language: Joi.string().min(2).max(5).optional(),
    timezone: Joi.string().optional(),
    features: Joi.object().pattern(Joi.string(), Joi.boolean()).optional(),
    limits: Joi.object({
      users: Joi.number().integer().min(1).optional(),
      storage: Joi.number().integer().min(1).optional(),
      apiCalls: Joi.number().integer().min(1).optional()
    }).optional()
  }),
  
  updateSubscription: Joi.object({
    startDate: Joi.date().optional(),
    endDate: Joi.date().optional(),
    autoRenew: Joi.boolean().optional(),
    paymentMethod: Joi.string().optional()
  }),
  
  suspendTenant: Joi.object({
    reason: Joi.string().max(500).optional()
  }),
  
  checkDomain: Joi.object({
    domain: Joi.string().min(3).max(63).pattern(/^[a-z0-9-]+$/).required()
  })
};

class TenantController {
  // 创建租户
  async createTenant(request, reply) {
    try {
      const { error, value } = schemas.createTenant.validate(request.body);
      if (error) {
        return reply.code(400).send({
          success: false,
          message: 'Validation error',
          errors: error.details.map(detail => detail.message)
        });
      }
      
      const result = await tenantService.createTenant(value);
      
      reply.code(201).send({
        success: true,
        data: result,
        message: 'Tenant created successfully'
      });
      
    } catch (error) {
      request.log.error(error);
      
      if (error.message.includes('already exists') || 
          error.message.includes('Invalid domain')) {
        return reply.code(409).send({
          success: false,
          message: error.message
        });
      }
      
      reply.code(500).send({
        success: false,
        message: 'Failed to create tenant'
      });
    }
  }
  
  // 获取租户列表
  async getTenants(request, reply) {
    try {
      const options = {
        page: parseInt(request.query.page) || 1,
        limit: parseInt(request.query.limit) || 20,
        status: request.query.status,
        plan: request.query.plan,
        search: request.query.search,
        sortBy: request.query.sortBy || 'createdAt',
        sortOrder: request.query.sortOrder || 'desc'
      };
      
      // 限制每页最大数量
      if (options.limit > 100) {
        options.limit = 100;
      }
      
      const result = await tenantService.getTenants(options);
      
      reply.send({
        success: true,
        data: result,
        message: 'Tenants retrieved successfully'
      });
      
    } catch (error) {
      request.log.error(error);
      
      reply.code(500).send({
        success: false,
        message: 'Failed to retrieve tenants'
      });
    }
  }
  
  // 获取租户详情
  async getTenant(request, reply) {
    try {
      const { tenantId } = request.params;
      
      const result = await tenantService.getTenantById(tenantId);
      
      reply.send({
        success: true,
        data: result,
        message: 'Tenant retrieved successfully'
      });
      
    } catch (error) {
      request.log.error(error);
      
      if (error.message.includes('not found')) {
        return reply.code(404).send({
          success: false,
          message: error.message
        });
      }
      
      reply.code(500).send({
        success: false,
        message: 'Failed to retrieve tenant'
      });
    }
  }
  
  // 更新租户信息
  async updateTenant(request, reply) {
    try {
      const { tenantId } = request.params;
      const { error, value } = schemas.updateTenant.validate(request.body);
      
      if (error) {
        return reply.code(400).send({
          success: false,
          message: 'Validation error',
          errors: error.details.map(detail => detail.message)
        });
      }
      
      const result = await tenantService.updateTenant(tenantId, value);
      
      reply.send({
        success: true,
        data: result,
        message: 'Tenant updated successfully'
      });
      
    } catch (error) {
      request.log.error(error);
      
      if (error.message.includes('not found')) {
        return reply.code(404).send({
          success: false,
          message: error.message
        });
      }
      
      if (error.message.includes('already exists')) {
        return reply.code(409).send({
          success: false,
          message: error.message
        });
      }
      
      reply.code(500).send({
        success: false,
        message: 'Failed to update tenant'
      });
    }
  }
  
  // 更新租户设置
  async updateTenantSettings(request, reply) {
    try {
      const { tenantId } = request.params;
      const { error, value } = schemas.updateSettings.validate(request.body);
      
      if (error) {
        return reply.code(400).send({
          success: false,
          message: 'Validation error',
          errors: error.details.map(detail => detail.message)
        });
      }
      
      const result = await tenantService.updateTenantSettings(tenantId, value);
      
      reply.send({
        success: true,
        data: result,
        message: 'Tenant settings updated successfully'
      });
      
    } catch (error) {
      request.log.error(error);
      
      if (error.message.includes('not found')) {
        return reply.code(404).send({
          success: false,
          message: error.message
        });
      }
      
      reply.code(500).send({
        success: false,
        message: 'Failed to update tenant settings'
      });
    }
  }
  
  // 删除租户
  async deleteTenant(request, reply) {
    try {
      const { tenantId } = request.params;
      
      const result = await tenantService.deleteTenant(tenantId);
      
      reply.send({
        success: true,
        data: result,
        message: 'Tenant deleted successfully'
      });
      
    } catch (error) {
      request.log.error(error);
      
      if (error.message.includes('not found')) {
        return reply.code(404).send({
          success: false,
          message: error.message
        });
      }
      
      if (error.message.includes('Cannot delete')) {
        return reply.code(409).send({
          success: false,
          message: error.message
        });
      }
      
      reply.code(500).send({
        success: false,
        message: 'Failed to delete tenant'
      });
    }
  }
  
  // 激活租户
  async activateTenant(request, reply) {
    try {
      const { tenantId } = request.params;
      
      const result = await tenantService.activateTenant(tenantId);
      
      reply.send({
        success: true,
        data: result,
        message: 'Tenant activated successfully'
      });
      
    } catch (error) {
      request.log.error(error);
      
      if (error.message.includes('not found')) {
        return reply.code(404).send({
          success: false,
          message: error.message
        });
      }
      
      reply.code(500).send({
        success: false,
        message: 'Failed to activate tenant'
      });
    }
  }
  
  // 停用租户
  async deactivateTenant(request, reply) {
    try {
      const { tenantId } = request.params;
      
      const result = await tenantService.deactivateTenant(tenantId);
      
      reply.send({
        success: true,
        data: result,
        message: 'Tenant deactivated successfully'
      });
      
    } catch (error) {
      request.log.error(error);
      
      if (error.message.includes('not found')) {
        return reply.code(404).send({
          success: false,
          message: error.message
        });
      }
      
      reply.code(500).send({
        success: false,
        message: 'Failed to deactivate tenant'
      });
    }
  }
  
  // 暂停租户
  async suspendTenant(request, reply) {
    try {
      const { tenantId } = request.params;
      const { error, value } = schemas.suspendTenant.validate(request.body);
      
      if (error) {
        return reply.code(400).send({
          success: false,
          message: 'Validation error',
          errors: error.details.map(detail => detail.message)
        });
      }
      
      const result = await tenantService.suspendTenant(tenantId, value.reason);
      
      reply.send({
        success: true,
        data: result,
        message: 'Tenant suspended successfully'
      });
      
    } catch (error) {
      request.log.error(error);
      
      if (error.message.includes('not found')) {
        return reply.code(404).send({
          success: false,
          message: error.message
        });
      }
      
      reply.code(500).send({
        success: false,
        message: 'Failed to suspend tenant'
      });
    }
  }
  
  // 获取租户统计信息
  async getTenantStats(request, reply) {
    try {
      const { tenantId } = request.params;
      
      const result = await tenantService.getTenantStats(tenantId);
      
      reply.send({
        success: true,
        data: result,
        message: 'Tenant stats retrieved successfully'
      });
      
    } catch (error) {
      request.log.error(error);
      
      if (error.message.includes('not found')) {
        return reply.code(404).send({
          success: false,
          message: error.message
        });
      }
      
      reply.code(500).send({
        success: false,
        message: 'Failed to retrieve tenant stats'
      });
    }
  }
  
  // 更新租户订阅
  async updateSubscription(request, reply) {
    try {
      const { tenantId } = request.params;
      const { error, value } = schemas.updateSubscription.validate(request.body);
      
      if (error) {
        return reply.code(400).send({
          success: false,
          message: 'Validation error',
          errors: error.details.map(detail => detail.message)
        });
      }
      
      const result = await tenantService.updateSubscription(tenantId, value);
      
      reply.send({
        success: true,
        data: result,
        message: 'Subscription updated successfully'
      });
      
    } catch (error) {
      request.log.error(error);
      
      if (error.message.includes('not found')) {
        return reply.code(404).send({
          success: false,
          message: error.message
        });
      }
      
      reply.code(500).send({
        success: false,
        message: 'Failed to update subscription'
      });
    }
  }
  
  // 检查域名可用性
  async checkDomainAvailability(request, reply) {
    try {
      const { error, value } = schemas.checkDomain.validate(request.body);
      
      if (error) {
        return reply.code(400).send({
          success: false,
          message: 'Validation error',
          errors: error.details.map(detail => detail.message)
        });
      }
      
      const result = await tenantService.checkDomainAvailability(value.domain);
      
      reply.send({
        success: true,
        data: result,
        message: 'Domain availability checked'
      });
      
    } catch (error) {
      request.log.error(error);
      
      reply.code(500).send({
        success: false,
        message: 'Failed to check domain availability'
      });
    }
  }
  
  // 获取功能使用情况
  async getFeatureUsage(request, reply) {
    try {
      const { tenantId } = request.params;
      
      const result = await tenantService.getFeatureUsage(tenantId);
      
      reply.send({
        success: true,
        data: result,
        message: 'Feature usage retrieved successfully'
      });
      
    } catch (error) {
      request.log.error(error);
      
      if (error.message.includes('not found')) {
        return reply.code(404).send({
          success: false,
          message: error.message
        });
      }
      
      reply.code(500).send({
        success: false,
        message: 'Failed to retrieve feature usage'
      });
    }
  }
  
  // 获取当前租户信息（用于租户用户）
  async getCurrentTenant(request, reply) {
    try {
      const tenantId = request.tenantId;
      
      if (!tenantId) {
        return reply.code(400).send({
          success: false,
          message: 'Tenant context required'
        });
      }
      
      const result = await tenantService.getTenantById(tenantId);
      
      reply.send({
        success: true,
        data: result,
        message: 'Current tenant retrieved successfully'
      });
      
    } catch (error) {
      request.log.error(error);
      
      if (error.message.includes('not found')) {
        return reply.code(404).send({
          success: false,
          message: error.message
        });
      }
      
      reply.code(500).send({
        success: false,
        message: 'Failed to retrieve current tenant'
      });
    }
  }
  
  // 更新当前租户设置（用于租户管理员）
  async updateCurrentTenantSettings(request, reply) {
    try {
      const tenantId = request.tenantId;
      
      if (!tenantId) {
        return reply.code(400).send({
          success: false,
          message: 'Tenant context required'
        });
      }
      
      const { error, value } = schemas.updateSettings.validate(request.body);
      
      if (error) {
        return reply.code(400).send({
          success: false,
          message: 'Validation error',
          errors: error.details.map(detail => detail.message)
        });
      }
      
      const result = await tenantService.updateTenantSettings(tenantId, value);
      
      reply.send({
        success: true,
        data: result,
        message: 'Tenant settings updated successfully'
      });
      
    } catch (error) {
      request.log.error(error);
      
      if (error.message.includes('not found')) {
        return reply.code(404).send({
          success: false,
          message: error.message
        });
      }
      
      reply.code(500).send({
        success: false,
        message: 'Failed to update tenant settings'
      });
    }
  }
}

module.exports = new TenantController();